package com.onlineauction.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.onlineauction.entities.Item;
import com.onlineauction.helpers.Constants;
import com.onlineauction.helpers.Constants.Category;

public class AddItemServlet extends HttpServlet {

	private static final long serialVersionUID = -4198527463061318990L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,
			ServletException {

		HttpSession session = request.getSession(true);
		String username = (String) session.getAttribute(Constants.USERNAME);

		// user not logged in
		if (username == null) {
			response.sendRedirect("/LoginAccount");
			return;
		}

		String productName = request.getParameter(Constants.PRODUCT_NAME);
		Category category = null;
		try {
			category = Category.valueOf(request.getParameter(Constants.CATEGORY));
		} catch (Exception e) {
			category = null;
		}

		if (productName == null || productName.length() == 0 || category == null) {
			String message = "Item name and category should be entered properly.";
			request.setAttribute(Constants.MESSAGE, message);
			request.getRequestDispatcher("/addItem.jsp").forward(request, response);
			return;
		}

		Item item = new Item(username, category, productName, true);
		String message = "Item added successfully.";
		response.sendRedirect("/Home");
		return;

	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		doGet(request, response);
	}
}
